package main

import (
	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"
	"html/template"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

type Doc struct {
	content string
}

func (doc *Doc) find(selection string) string {
	reg := regexp.MustCompile("<" + selection + ">(?s:(.*?))</" + selection + ">")
	v := reg.FindStringSubmatch(doc.content)
	if len(v) > 1 {
		return v[1]
	}
	return ""
}

func (doc *Doc) finds(selection string) []string {
	reg := regexp.MustCompile("<" + selection + ">(?s:(.*?))</" + selection + ">")
	v := reg.FindAllString(doc.content, -1)
	return v
}

type BlogDoc struct {
	FileName  string
	DirName   string
	Blog      string
	TitleImg  string
	FileInfos []os.FileInfo
	BlogId    string
}

func (blog *BlogDoc) Init(blogId string) error {
	blogFiles, err := ioutil.ReadDir(blogDir + "/" + blogId)
	if err != nil {
		return err
	}
	blog.BlogId = blogId
	blog.FileInfos = blogFiles
	return nil
}

func (blog *BlogDoc) BlogContent() BlogInfo {
	blogFiles := blog.FileInfos
	blogId := blog.BlogId
	var blogV BlogInfo
	var messages []Message
	for j := range blogFiles {
		//博客目录下子目录  包含博客txt文件  图片文件得目录
		blogFile := blogFiles[j]
		if blogFile.Name() == "remark" {
			remarkBytes, err := ioutil.ReadFile(blogDir + "/" + blog.BlogId + "/remark/remark.txt")
			if err != nil {
				continue
			}
			remarkTxt := string(remarkBytes)
			doc := Doc{content: remarkTxt}
			remarks := doc.finds("remark")
			for _, remark := range remarks {
				tDoc := Doc{remark}
				messages = append(messages, Message{
					Name: tDoc.find("name"),
					Msg:  template.HTML(tDoc.find("msg")),
				})
			}
			continue
		}
		//如果是文件
		if !blogFile.IsDir() {
			blogBytes, err := ioutil.ReadFile(blogDir + "/" + blog.BlogId + "/" + blogFile.Name())
			if err != nil {
				return blogV
			}
			blog := string(blogBytes)
			blogName := blogFile.Name()
			blogName = strings.ReplaceAll(blogName, ".txt", "")
			doc := Doc{content: blog}
			title := doc.find("t")
			date := doc.find("date")
			dates := strings.Split(date, ".")
			lastEditDate := doc.find("lastEditDate")
			content := doc.find("content")
			unsafe := blackfriday.MarkdownCommon([]byte(content))
			html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
			blogV = BlogInfo{
				Name:         blogName,
				Title:        title,
				Year:         dates[0],
				Moth:         dates[1],
				Day:          dates[2],
				BlogId:       blogId,
				LastEditDate: lastEditDate,
				Content:      template.HTML(html),
				Remarks:      messages,
			}
		}
	}
	blogV.Remarks = messages
	return blogV
}
